#include "OpenCV.h"
#include <Vfw.h>


/**********************
 * Constructor
 */
COpenCV::COpenCV() :
                m_Camera(NULL),
    original(NULL)
{
}
// end


/**********************
 * Destructor
 */
COpenCV::~COpenCV()
{
        StopCapture();
}
// end


/////////////////////////////////////////////////////////////////////////
//
/////////////////////////////////////////////////////////////////////////


/**********************
 * Pulls the image from the video stream and converts it to a
 * variety of formats for some strange reason
 */
bool COpenCV::StartCapture(int width, int height)
{
        StopCapture();

        m_Camera = cvCreateCameraCapture(0);

        if(IsCaptureStarted() == false)
        {
                return false;
        }

        cvSetCaptureProperty(m_Camera, CV_CAP_PROP_FRAME_WIDTH, width);

        if(GetImageSizes(width, height) == false)
        {
                return false;
        }

        IplImage *image = cvQueryFrame(m_Camera);
        cv::Mat frame(image);
        cv::flip(frame, frame, 1);

        CvSize imageSize = cvGetSize(image);

        original = cvCreateImage(imageSize, 8, 3);
        original->origin = image->origin;

        return true;
}
// end


/**********************
 * Stops video capture, and clears images
 */
bool COpenCV::StopCapture()
{
        if(m_Camera == NULL)
        {
                return false;
        }

        if(m_Camera != NULL)
        {
                cvReleaseCapture(&m_Camera);
                m_Camera = NULL;
        }

        if(original != NULL)
        {
                cvReleaseImage(&original);
                original = NULL;
        }

        return true;
}
// end


/**********************
 * Returns size of images
 */
bool COpenCV::GetImageSizes(int &width, int &height) const
{
        if(IsCaptureStarted() == false)
        {
                return false;
        }

        IplImage *cvimage = cvQueryFrame(m_Camera);

        width	= cvimage->width;
        height	= cvimage->height;

        return true;
}
// end


/////////////////////////////////////////////////////////////////////////
//
/////////////////////////////////////////////////////////////////////////


/**********************
 * Pulls images from camera
 */
IplImage* COpenCV::QueryFrame()
{
        if(IsCaptureStarted() == false)
        {
                return NULL;
        }

        IplImage *image = cvQueryFrame(m_Camera);
        cv::Mat frame(image);
        cv::flip(frame, frame, 1);
        cvCvtColor(image, original, CV_BGR2RGB);
        cvFlip(original);

        return original;
}
// end

/**********************
 *
 */
IplImage* COpenCV::GetImage()
{
    return original;
}
// end
